{% extends "base.html" %}

{% set active_page = "Database" %}

{% set query_url = "/database/browse?query=" %}
{% set general_analysis_elements = [
    ("device name", firmware.device_name, "", '{"device_name": {"$eq": "PLACEHOLDER"}}'),
    ("device_part", firmware.part, "", '{"device_part": {"$eq": "PLACEHOLDER"}}'),
    ("vendor", firmware.vendor, "", '{"vendor": {"$eq": "PLACEHOLDER"}}'),
    ("device_class", firmware.device_class, "", '{"device_class": {"$eq": "PLACEHOLDER"}}'),
    ("version", firmware.version, "", ""),
    ("release date", firmware.release_date, "", ""),
    ("file name", firmware.file_name, "word-break: break-all; word-wrap: break-word;", ""),
    ("virtual_path", firmware.get_virtual_paths_for_one_uid(root_uid=root_uid)|nice_list|replace_uid_with_hid|safe, "word-break: break-all; overflow-wrap: break-word;", ""),
    ("file size", firmware.size|number_format(verbose=True), "", ""),
    ("MD5", firmware.md5, "word-break: break-all;", ""),
    ("SHA256", firmware.sha256, "word-break: break-all;", ""),
    ("Tags", firmware.tags|render_tags(size=12)|safe, "", ""),
    ("Analysis Tags", firmware.analysis_tags | render_analysis_tags(size=12) | safe, "", "")
] -%}

{% block head %}

	{# jstree import #}
    <script src="{{ url_for('static', filename='jstree/dist/jstree.min.js') }}"></script>
    <link rel="stylesheet" href="{{ url_for('static', filename='jstree/dist/themes/default/style.min.css') }}" />


	{# highlight.js import #}
    <script src="{{ url_for('static', filename='highlight.js/highlight.pack.js') }}"></script>
    <link rel="stylesheet" href="{{ url_for('static', filename='highlight.js/styles/github.css') }}" />

{% endblock %}

{% block body %}

{# firmware comparison from analysis #}

<div class="row" style="padding-right: 15px">
    {%if known_comparisons %}
        <div class="pull-right">
            <span class="glyphicon glyphicon-hdd" data-toggle="collapse" data-target="#old_comparisons" style="padding: 5px; margin-right: 5px;" title="Show List of Known Comparisons"></span>
        </div>
    {% endif %}
    {% if not uids_for_comparison or uid not in uids_for_comparison %}
        <div class="pull-right">
            <span class="glyphicon glyphicon-plus" onclick="location.href='/comparison/add/{{ uid }}'" style="padding: 5px; margin-right: 5px;" title="Add to Comparison"></span>
        </div>
    {% endif %}

    {% if uids_for_comparison %}
        <div class="pull-right">
            <span class="glyphicon glyphicon-list" data-toggle="collapse" data-target="#comparison-list" style="padding: 5px; margin-right: 5px;" title="Show Selected Firmwares for Comparison"></span>
        </div>
    {% endif %}
    <div class="pull-right">
        <h5 style="margin-top: 4px; margin-bottom: 0; margin-right: 5px">Comparisons</h5>
    </div>
</div>

<div class="collapse" id="old_comparisons">
    <div class="jumbotron pull-right" style="float: left; padding: 10px; margin-bottom: 0; margin-left: 15px; margin-right: 15px; width: auto; max-width: 650px; border: 1px solid #ddd; background-color: #f8f8f8;">
        <h4 style="margin-top: 0; text-align: center;">List of Comparisons Containing the Displayed Firmware</h4>
            <hr style="margin: 12px">
                <div class="card card-body">
                    {% for comparison in known_comparisons%}
                            <div class="col-xs-12" style="padding: 0;">
                                <span style="padding: 2px; margin: 0; display: -webkit-inline-box; display: ">
                                    <span button type="button" class="btn btn-primary btn-sm" style="margin-left: 3px" onclick="location.href='/compare/{{ comparison[0]}}'">{{ comparison[0] | replace_comparison_uid_with_hid | safe  }}</span>
                                </span>
                            </div>
                        {% endfor %}
                </div>
    </div>
</div>

{% if uids_for_comparison %}
<div class="row" style="margin-bottom: 15px">
    <div class="row collapse" id="comparison-list" style="margin: 0">
        <div class="jumbotron pull-right" style="float: left; padding: 10px; margin-bottom: 0; margin-left: 15px; margin-right: 15px; width: auto; max-width: 650px; border: 1px solid #ddd; background-color: #f8f8f8;">
            <h4 style="margin-top: 0; text-align: center;">Firmwares Selected for Comparison</h4>
            <hr style="margin: 12px">
            <table width="auto">
                <tr>
                    <td style="width: 10px; vertical-align: top;">
                {% for compare_uid in uids_for_comparison %}
                    <div class="col-xs-12" style="padding: 0;">
                        <span style="padding: 2px; margin: 0; display: -webkit-inline-box; display: ">
                            <span class="close" style="font-size: 20px" onclick="location.href='/comparison/remove/{{ uid }}/{{ compare_uid }}'">
                                &times;
                            </span>
                            <span class="tag label label-{% if compare_uid == uid %}primary{% else %}default{% endif %}" style="margin-left: 3px">{{ compare_uid|replace_uid_with_hid|safe }}</span>
                        </span>
                    </div>
                {% endfor %}
            </div>
                    </td>
            {% if uids_for_comparison|length > 1 %}
                    <td style="width: 180px; vertical-align: top;">
                    <div class="col-xs-12" style="padding: 2px;">
                        <button type="button" class="btn btn-default btn-xs" onclick="location.href='/comparison/remove_all/{{ uid }}'" style="width: 100%">
                            <span class="glyphicon glyphicon-remove"></span> Remove All
                        </button>
                    </div>
                    <div class="col-xs-12" style="padding: 2px;">
                        <button type="button" id="start_compare_button" class="btn btn-default btn-xs" style="width: 100%">
                            <span class="glyphicon glyphicon-duplicate"></span> Compare
                        </button>
                    </div>
                    <div class="form-group col-xs-12" style="margin: 0;">
                        <div class="checkbox" style="margin: 0; margin-left: 30px; text-align: center">
                            <label style="padding: 2px">
                                <input type="checkbox" value="true" id="recompare_checkbox" style="margin-top: 2px;"> Force Recompare
                            </label>
                        </div>
                    </div>
                    <script>
                        function start_compare(){
                            var checkbox = document.getElementById('recompare_checkbox');
                            var link = '/compare';
                            if (checkbox.checked) link += '?force_recompare=true';
                            location.href = link;
                        };
                        document.getElementById("start_compare_button").onclick = start_compare;
                    </script>
                </div>
                    </td>
            {% endif %}
                </tr>
            </table>
        </div>
    </div>
    {% endif %}
</div>

<div style="word-wrap: break-word">
    <h2>Analysis for <span class="text-primary">{{ firmware.get_hid(root_uid=root_uid) }}</span><br /><small><strong>UID:</strong> {{ uid|safe }}</small></h2>
</div>

{% if all_analyzed_flag %}
<div class="alert alert-warning">
  <strong>Warning!</strong> Not all included files are fully analyzed yet! Only analyzed files are shown.
</div>
{% endif %}

<div class="row">

    {# general info section section #}


    <div class="col-lg-6">
        <table class="table table-bordered table-hover" width="800" valign="center" align="center" border="0">
            <tr class="success" align="center">
                <th class="result" colspan="2" width="100">General</th>
            </tr>
            {% for label, content, style, query in general_analysis_elements %}
                {% if content %}
                    <tr>
                        <td class="active result" width="150">{{ label | replace_underscore }}</td>
                        <td class="active result{% if query %} clickable{% endif %}" {% if style %} style="{{ style }}" {% endif %}
                                {% if query %}onclick="location.href='{{ query_url + query.replace("PLACEHOLDER", content) | urlencode }}'" data-toggle="tooltip" title="show other firmwares of {{content}}" {% endif %}>
                            {% if label == "release date" and content == "1970-01-01" %}
                                unknown
                            {% else %}
                                {{ content }}
                            {% endif %}
                        </td>
                    </tr>
                {% endif %}
            {% endfor %}
            {% if "file_type" in firmware.processed_analysis %}
            	<tr class="active">
                	<td class="result" width="150">file type</td>
                    <td class="result" style="{{ style }}">{{ firmware.processed_analysis["file_type"]["full"] }}</td>
				</tr>
			{% endif %}
            {% if firmware_including_this_fo %}
            	<tr class="active">
                	<td class="result" width="150">firmwares including this files</td>
                    <td class="result" style="{{ style }}">{{ firmware_including_this_fo | nice_uid_list() | safe }}</td>
				</tr>
			{% endif %}
            {% if other_versions %}
            	<tr class="active">
                	<td class="result" width="150">other versions</td>
                    <td class="result" style="{{ style }}">
                                <button data-toggle="collapse" data-target="#other_versions" class="list-group-item list-group-item-info">
                                    <span class="badge">{{ other_versions | length }}</span> show files
                                </button>
                                <div id="other_versions" class="collapse">
                                    {% for version in other_versions %}
                                        <a {% if selected_analysis %} href="/analysis/{{ version._id }}/{{selected_analysis}}"
                                           {% else %} href="/analysis/{{ version._id }}"{% endif %} class="list-group-item">
                                            <p class="list-group-item-text">
                                                {{ version.version }}
                                            </p>
                                        </a>
                                    {% endfor %}
                                </div>
                    </td>
				</tr>
			{% endif %}
        </table>
    </div>

    {# processed analysis section #}

    <div class="col-lg-6">
        <table class="table table-bordered table-hover result">
            <th class="success"> Analysis Results </th>

            {% for analysis_plugin in firmware.processed_analysis|sort %}
                <tr>
                    <td class="active result clickable" onclick="location.href='/analysis/{{ uid|safe }}/{{analysis_plugin}}/ro/{{ root_uid }}'"
                     data-toggle="tooltip" title="{{ analysis_plugin_dict.get(analysis_plugin, ['not available'])[0] | safe }}">
                        {{ analysis_plugin | replace_underscore }}
                    </td>
                </tr>
            {% endfor %}
        </table>
    </div>

    {# included files file tree section #}
    <div class="col-lg-12">
    	<table class="table table-bordered" width="800" valign="center" align="center" border="0">
            <tr class="success" align="center">
                <th class="result">File Tree</th>
            </tr>
    		<tr>
    			<td>
                    <div id="fileTreeAjax"></div>

                    <script>
                        $('#fileTreeAjax')
                            // generate links to the analysis page
                            .on("activate_node.jstree", function(e,data){window.location.href = data.node.a_attr.href;})
                            // generate file tree
                            .jstree({
                              "core" : {
                                'data' : {
                                  'url' : function (node) {
                                    return node.id === '#' ?
                                        "/ajax_root/{{ uid|safe }}" : "/ajax_tree/" + node["data"]["uid"] + "/{{ root_uid|safe }}";
                                  }
                                }
                              },
                              "plugins" : [ "sort" ]
                            });
                    </script>
    			</td>
    		</tr>
    	</table>
    </div>

    {# block for showing an analysis #}

    {% block complete_analysis_block %}

    <div class="col-lg-12">
        {% block analysis_result %}
        {% endblock %}
    </div>

    {% if summary_of_included_files %}
    <div class="col-lg-12">
    	<table class="table table-bordered result">
			<colgroup>
				<col width="100">
				<col width="700">
			</colgroup>
			<tr>
				<th class="success result" colspan=2>Summary Including Results of Included Files</th>
			</tr>
			<tr>
				<td class="active result">item count</td>
				<td class="active result">{{ summary_of_included_files | length }}
			</tr>
		{% for item in summary_of_included_files|sort %}
    		<tr>
				<td class="result">{{ item | wordwrap(width=60, break_long_words=True) }}</td>
				<td class="result">
					{{ summary_of_included_files[item] | nice_uid_list(root_uid=root_uid, selected_analysis=selected_analysis) | safe }}
				</td>
			</tr>
    	{% endfor %}
    	</table>
    </div>
    {% endif %}


    {% endblock %}

    {# preview section #}
    {% if "file_type" in firmware.processed_analysis %}
	    {% set previewable_mime_types = [] %}
	    {% if firmware.processed_analysis["file_type"]['mime'] in previewable_mime_types
	    or firmware.processed_analysis["file_type"]['mime'][0:5] == "text/"
	    or firmware.processed_analysis["file_type"]['mime'][0:6] == "image/" %}

		    <div class="col-lg-12">
		        <button id="preview_button" data-toggle="collapse" data-target="#preview-div" class="list-group-item list-group-item-info">
		            <b style="color:#f8f8f8;">Show Preview</b>
		        </button>
		        <div id="preview-div" class="collapse">
		            <div id="preview-loading-gif" style="display: block; border: 1px solid; border-color: #dddddd; padding: 5px; text-align: center">
		                <img src="{{ url_for("static", filename = "Pacman.gif") }}">
		            </div>
		        </div>
		        <script>
		            var loading_gif = document.getElementById("preview-loading-gif");
		            function init_preview() {
		                hide_gif();
		                highlight_code();
		            };
		            function hide_gif() {
		                loading_gif.style.display = "none";
		            };
		            function highlight_code() {
		                var block = $('div#preview-div pre')[0];
                        hljs.highlightBlock(block);
		            };
		            function load_preview(){
		                loading_gif.style.display = "block";
		                document.getElementById("preview_button").onclick = function() {return false;};
		                $("#preview-div").load("/ajax_get_binary/{{ firmware.processed_analysis["file_type"]["mime"].replace("/", "_") }}/{{ uid|safe }}", init_preview);
		            };
		            document.getElementById("preview_button").onclick = load_preview;
		        </script>
		    </div>

	    {% endif %}
	{% endif %}


    {# comment section #}

    <div class="col-lg-12" style="margin-top: 20px">
        <table class="table table-bordered" valign="center" align="center" border="0" id="comments-head" style="margin-bottom:0;">
            <thead>
                <tr class="success" align="center">
                    <th class="result" valign="baseline">
                        Comments
                        {# Add Comment Button #}
                        <form action="/comment/{{ firmware.get_uid() }}" style="float: right; margin-right: 5px;">
                            <button class="btn btn-primary" type="submit">
                                <span class="glyphicon glyphicon-edit"></span> add comment
                            </button>
                        </form>

                        {# Show Comments Button #}
                        <form onsubmit="return false;" style="float: right; margin-right: 5px;">
                            <button data-toggle="collapse" data-target="#comments" class="btn btn-primary"
                            {% if firmware.comments | length == 0 %} disabled {% endif %}>
                                <span class="badge">{{ firmware.comments | length }}</span> show comments
                            </button>
                        </form>
                    </th>
                </tr>
            </thead>
        </table>
        {% if firmware.comments %}
        <div class="collapse" id="comments" style="margin:0;">
            <table class="table table-bordered" valign="center" align="center" border="0" id="comments-table" style="margin-bottom:0;">
                <tbody>
                    {% for comment in firmware.comments|sort_comments %}
                    <tr>
                        <td width="20%" valign="bottom">
                            <div>{{ comment.author }}</div>
                            <div>{{ comment.time|int|nice_unix_time }}</div>
                        </td>
                        <td width="80%" style="margin:0; padding:0;">
                            <pre style="white-space: pre-wrap; margin-bottom:0;">{{ comment.comment|urlize }}</pre>
                        </td>
                        <td style="margin:0; padding:0;">
                            {# Comment Delete Button #}
                            {% if firmware.vendor %}
                                <button data-toggle="collapse" data-target="#delete-button-div-{{ comment.time }}" class="btn btn-xs">
                                    <span class="glyphicon glyphicon-trash"></span>
                                </button>
                            {% endif %}
                        </td>
                        <td style="margin:0; padding:0;">
                            {# Comment Delete Confirm Button #}
                            {% if firmware.vendor %}
                                <div class="collapse" id="delete-button-div-{{ comment.time }}">
                                    <button class="btn btn-danger" type="button" onclick='window.location.href = "/admin/delete_comment/{{ uid }}/{{ comment.time }}";'>
                                        <span class="glyphicon glyphicon-ok"></span> click here to confirm!
                                    </button>
                                </div>
                            {% endif %}
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% endif %}
    </div>



</div>


{# Buttons #}
<div class="row" style="margin-top: 20px">

	{# user buttons #}
	<div class="col-lg-6 col-md-12">
	    <div class="alert alert-custom" style="padding:5px;">
	    	<strong>user options:</strong>
            {# Hex View Button #}
            <form action="/hex-dump/{{ firmware.get_uid() }}" style="display: inline" onsubmit="window.open('', 'formpopup', 'width=800,height=400,resizeable,scrollbars');this.target = 'formpopup';">
                <button class="btn btn-default" type="submit">
                    <span class="glyphicon glyphicon-eye-open"></span> show header in hex
                </button>
            </form>
            {# Radare Button #}
            <form action="/radare-view/{{ firmware.get_uid() }}" style="display: inline" target="_blank">
                <button class="btn btn-default" type="submit">
                    <span class="glyphicon glyphicon-console"></span> view in radare
                </button>
            </form>
            {# Binary Download Button #}
            <form action="/download/{{ firmware.get_uid() }}" style="display:inline">
                <button class="btn btn-default" type="submit">
                    <span class="glyphicon glyphicon-download-alt"></span> download raw file
                </button>
            </form>
 			{# Tar Download Button #}
			{% if firmware.files_included %}
				<form action="/tar-download/{{ firmware.get_uid() }}" style="display:inline">
			    	<button class="btn btn-default" type="submit">
			        	<span class="glyphicon glyphicon-compressed"></span> download included files as tar.gz
			        </button>
				</form>
			{% endif %}
			{# Update Analysis Buttons #}
			{% if firmware.vendor %}
                <form action="/update-analysis/{{ firmware.get_uid() }}" style="display:inline">
                    <button class="btn btn-default" type="submit">
                        <span class="glyphicon glyphicon-repeat"></span> update analysis
                    </button>
                </form>
			{% endif %}
			{# Start Binary Search Button #}
			{% if firmware.vendor %}
                <button class="btn btn-default" onclick='window.location.href = "/database/binary_search?firmware_uid={{ firmware.get_uid() }}";'>
                    <span class="glyphicon glyphicon-search"></span> YARA search
                </button>
			{% endif %}
	    </div>
    </div>
    {# admin buttons #}
    {% if firmware.vendor and user_has_admin_clearance %}
    <div class="col-lg-6 col-md-12">
	    <div class="alert alert-custom" style="padding:5px;">
            <strong>admin options:</strong>
    		{# Update Analysis Buttons #}
		    <button data-toggle="collapse" data-target="#re-do-button-div" class="btn btn-default">
	            <span class="glyphicon glyphicon-repeat"></span> re-do analysis
	        </button>
	        <span class="collapse" id="re-do-button-div">
	            <button class="btn btn-danger" type="button" onclick='window.location.href = "/admin/re-do_analysis/{{ uid }}";'>
	                <span class="glyphicon glyphicon-ok"></span> confirm: This action will delete all previous results and data including comments!
	            </button>
	        </span>
		    {# FW Delete Confirm Button #}
		   	<button data-toggle="collapse" data-target="#delete-button-div" class="btn btn-default">
		    	<span class="glyphicon glyphicon-trash"></span> delete firmware
		    </button>
	        <span class="collapse" id="delete-button-div">
	            <button class="btn btn-danger" type="button" onclick='window.location.href = "/admin/delete/{{ uid }}";'>
	                <span class="glyphicon glyphicon-ok"></span> click here to confirm removal!
	            </button>
	        </span>
	    </div>
    </div>
    {% endif %}
</div>


{% endblock %}
